package org.mxp.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class TextTableUtil {
    public static String getTableData(String text) {
        int width = 90;
        int height = 60;
        int fontSize = 12;
        int sX = 0;
        int sY = fontSize;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = image.createGraphics();
        // 设置文字属性
        graphics.setFont(new Font("宋体", Font.PLAIN, fontSize));
        graphics.setColor(Color.BLACK);
        String[] strList = text.split("");
        FontMetrics fm = graphics.getFontMetrics();
        String tempStr = "";
        Random random = new Random();
        for (String str: strList) {
            if (fm.stringWidth(tempStr + str) <= width) {
                graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
                graphics.drawString(str, sX, sY);
                sX += fm.stringWidth(str);
                tempStr += str;
            } else {
                sX = 0;
                sY += fontSize + 2;
                graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
                graphics.drawString(str, sX, sY);
                sX += fm.stringWidth(str);
                tempStr = str;
            }
        }
        String result = "";

        // 处理图像，转换文字为坐标点
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                int color = image.getRGB(x, y);
                Color colorResult = new Color(color, true);
                if (color != 0) { // 如果像素点不是背景色，则认为是文字的一部分
                    // 此处填充，x和y即为文字的坐标点
                    result += x + "," + y + "#rgb(" + colorResult.getRed() + ", " + colorResult.getGreen() + ", " + colorResult.getBlue() + ")|";
                    System.out.println("喷射数据：" + x + "," + y + "#rgb(" + colorResult.getRed() + ", " + colorResult.getGreen() + ", " + colorResult.getBlue() + ")");
                }
            }
        }

        // 将图片输出到本地文件系统
        File outputFile = new File("C:\\img\\textToPixels_" + new Date().getTime() + "_" + UUID.randomUUID().toString().replace("-", "") + ".png");
        try {
            ImageIO.write(image, "PNG", outputFile);
            System.out.println("Image saved successfully.");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error saving the image.");
        }

        if (!result.isEmpty()) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }
}
